import React, { useEffect } from "react";
import NavBar from "@/components/NavBar/NavBar";
import TakeCard from "@/components/TakeCard/TakeCard";
import { useNavigate } from "react-router-dom";
import { Button, Empty, Toast } from "antd-mobile";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import { fetchDefaultTakeIdThunk, fetchTakeListThunk } from "@/store/modules/takeStore";
import type { TakeAddress as TakeType } from "@/type/TakeType";
import "./TakeAddress.scss";

const TakeAddress = () => {
   const navigate = useNavigate();
   const enhanceDispatch = useEnhanceDispatch();
   const takeList: TakeType[] = useEnhanceSelector(state => state.takeStore.takeList);

   /**
    * @description 获取收货地址列表的回调函数
    * */
   const fetchTakeList = async () => {
      try {
         await enhanceDispatch(fetchTakeListThunk()).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    * @description 获取默认收货地址id的回调函数
    * */
   const fetchDefaultTakeId = async () => {
      try {
         await enhanceDispatch(fetchDefaultTakeIdThunk()).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   const renderTake = () => {
      if (takeList.length) {
         return takeList.map(item => <TakeCard key={item.address_id} take={item}></TakeCard>);
      } else {
         return <Empty description="暂无数据"></Empty>;
      }
   };

   useEffect(() => {
      fetchTakeList();
      fetchDefaultTakeId();
   }, []);

   return (
      <div className="take-address-container">
         <div className="header">
            <NavBar children="收货地址" backIcon onBack={() => navigate(-1)}></NavBar>
         </div>
         <div className="take-list">
            {
               renderTake()
            }
         </div>
         <div className="add-take">
            <Button color="primary" block>添加地址</Button>
         </div>
      </div>
   );
};

export default TakeAddress;
